package com.nl.boot.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.ConvertingCursor;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * spring redis 工具类.
 *
 * @author breggor
 **/
@Component
public class RedisOps {

    private final RedisTemplate redisTemplate;

    @Autowired
    public RedisOps(final RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 判断key 是否在redis中存在.
     *
     * @param key 缓存的减值
     * @return boolean
     */
    public Boolean exits(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 自增.
     *
     * @param key key
     * @return 自增结果
     */
    public Long increment(final String key) {
        return redisTemplate.opsForValue().increment(key);
    }

    /**
     * 自增delta.
     *
     * @param key   key
     * @param delta delta
     * @return 自增结果
     */
    public Long increment(final String key, final long delta) {
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等.
     *
     * @param <T>   类型
     * @param key   缓存的键值
     * @param value 缓存的值
     * @return 缓存的对象
     */
    public <T> ValueOperations<String, T> setCacheObject(final String key, final T value) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        operation.set(key, value);
        return operation;
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等.
     *
     * @param <T>      类型
     * @param key      缓存的键值
     * @param value    缓存的值
     * @param timeout  时间
     * @param timeUnit 时间颗粒度
     * @return 缓存的对象
     */
    public <T> ValueOperations<String, T> setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        operation.set(key, value, timeout, timeUnit);
        return operation;
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等.
     *
     * @param key      key
     * @param value    value
     * @param timeout  timeout
     * @param timeUnit timeUnit
     * @param <T>      类型
     * @return boolean
     */
    public <T> Boolean setIfAbsent(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) {
        Objects.requireNonNull(key, "key 不能为空");
        Objects.requireNonNull(value, "value 不能为空");
        Objects.requireNonNull(timeout, "timeout 不能为空");
        Objects.requireNonNull(timeUnit, "timeUnit 不能为空");
        return redisTemplate.opsForValue().setIfAbsent(key, value, timeout, timeUnit);
    }

    /**
     * 获得缓存的基本对象.
     *
     * @param <T> 类型
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 删除单个对象.
     *
     * @param key key
     */
    public void deleteObject(final String key) {
        redisTemplate.delete(key);
    }

    /**
     * 删除集合对象.
     *
     * @param col 集合
     */
    public void deleteObject(final Collection col) {
        redisTemplate.delete(col);
    }

    /**
     * 缓存List数据.
     *
     * @param <T>      类型
     * @param key      缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> ListOperations<String, T> setCacheList(final String key, final List<T> dataList) {
        ListOperations<String, T> listOperation = redisTemplate.opsForList();
        if (null != dataList) {
            for (T t : dataList) {
                listOperation.rightPush(key, t);
            }
        }
        return listOperation;
    }

    /**
     * 缓存List数据.
     *
     * @param <T>      类型
     * @param key      缓存的键值
     * @param dataList 待缓存的List数据
     * @param timeOut  缓存时间
     * @param timeUnit 缓存时间单位
     * @return 缓存的对象
     */
    public <T> ListOperations<String, T> setCacheList(final String key, final List<T> dataList, final Long timeOut, final TimeUnit timeUnit) {
        ListOperations<String, T> listOperation = redisTemplate.opsForList();
        if (null != dataList) {
            for (T t : dataList) {
                listOperation.rightPush(key, t);
            }
        }
        redisTemplate.expire(key, timeOut, timeUnit);
        return listOperation;
    }

    /**
     * 获得缓存的list对象.
     *
     * @param <T> 类型
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(final String key) {
        List<T> dataList = new ArrayList<T>();
        ListOperations<String, T> listOperation = redisTemplate.opsForList();
        Long size = listOperation.size(key);

        if (Objects.nonNull(size)) {
            for (int i = 0; i < size; i++) {
                dataList.add(listOperation.index(key, i));
            }
        }
        return dataList;
    }

    /**
     * 缓存Set.
     *
     * @param <T>     类型
     * @param key     缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet) {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        for (T t : dataSet) {
            setOperation.add(t);
        }
        return setOperation;
    }

    /**
     * 缓存Set.
     *
     * @param <T>     类型
     * @param key     缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet, final Long timeOut, final TimeUnit timeUnit) {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        for (T t : dataSet) {
            setOperation.add(t);
        }
        redisTemplate.expire(key, timeOut, timeUnit);
        return setOperation;
    }

    /**
     * 缓存Set item.
     *
     * @param <T>  类型
     * @param key  缓存键值
     * @param data 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSetItem(final String key, final T data) {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        setOperation.add(data);
        return setOperation;
    }

    /**
     * 获得缓存的set.
     *
     * @param <T> 类型
     * @param key key
     * @return Set
     */
    public <T> Set<T> getCacheSet(final String key) {
        Set<T> dataSet = new HashSet<T>();
        BoundSetOperations<String, T> operation = redisTemplate.boundSetOps(key);
        Long size = operation.size();
        if (Objects.nonNull(size)) {
            for (int i = 0; i < size; i++) {
                dataSet.add(operation.pop());
            }
        }
        return dataSet;
    }

    /**
     * 获得缓存的set size.
     *
     * @param key key
     * @return Set
     */
    public long getCacheSetSize(final String key) {
        BoundSetOperations<String, ?> operation = redisTemplate.boundSetOps(key);
        return Optional.ofNullable(operation.size()).orElse(0L);
    }

    /**
     * 缓存Map.
     *
     * @param <T>     类型
     * @param key     key
     * @param dataMap dataMap
     * @return HashOperations
     */
    public <T> HashOperations<String, String, T> setCacheMap(final String key, final Map<String, T> dataMap) {
        HashOperations<String, String, T> hashOperations = redisTemplate.opsForHash();
        if (null != dataMap) {
            for (Map.Entry<String, T> entry : dataMap.entrySet()) {
                hashOperations.put(key, entry.getKey(), entry.getValue());
            }
        }
        return hashOperations;
    }

    /**
     * 缓存Map.
     *
     * @param <T>      类型
     * @param key      key
     * @param dataMap  dataMap
     * @param timeout  timeout
     * @param timeUnit 单位
     * @return HashOperations
     */
    public <T> HashOperations<String, String, T> setCacheMap(final String key, final Map<String, T> dataMap, final Long timeout, final TimeUnit timeUnit) {
        HashOperations hashOperations = redisTemplate.opsForHash();
        if (null != dataMap) {
            for (Map.Entry<String, T> entry : dataMap.entrySet()) {
                hashOperations.put(key, entry.getKey(), entry.getValue());
            }
        }
        redisTemplate.expire(key, timeout, timeUnit);
        return hashOperations;
    }

    /**
     * 获得缓存的Map.
     *
     * @param <T> value类型
     * @param key key
     * @return Map
     */
    public <T> Map<String, T> getCacheMap(final String key) {
        return (Map<String, T>) redisTemplate.opsForHash().entries(key);
    }

    /**
     * 设置缓存Map key-value.
     *
     * @param <T>       类型
     * @param key       key
     * @param hashKey   hashKey
     * @param hashValue hashValue
     * @return T
     */
    public <T> HashOperations<String, String, T> setCacheMapValue(final String key, final String hashKey, final T hashValue) {
        HashOperations<String, String, T> hashOperations = redisTemplate.opsForHash();
        hashOperations.put(key, hashKey, hashValue);
        return hashOperations;
    }

    /**
     * 设置缓存Map key-value.
     * 注:此处过期时间会修改整个hash表的过期时间
     *
     * @param <T>       类型
     * @param key       key
     * @param hashKey   hashKey
     * @param hashValue hashValue
     * @param timeout   timeout
     * @param timeUnit  timeUnit
     * @return T
     */
    public <T> HashOperations<String, String, T> setCacheMapValue(final String key, final String hashKey, final T hashValue,
                                                                  final Long timeout, final TimeUnit timeUnit) {
        HashOperations<String, String, T> hashOperations = redisTemplate.opsForHash();
        hashOperations.put(key, hashKey, hashValue);
        redisTemplate.expire(key, timeout, timeUnit);
        return hashOperations;
    }

    /**
     * 获得缓存Map 的value.
     *
     * @param <T>     类型
     * @param key     key
     * @param hashKey hashKey
     * @return T
     */
    public <T> T getCacheMapValue(final String key, final String hashKey) {
        return (T) redisTemplate.opsForHash().get(key, hashKey);
    }

    /**
     * 删除缓存Map 的指定key.
     *
     * @param key     key
     * @param hashKey hashKey
     * @return T
     */
    public Long deleteCacheMapKeys(final String key, final String... hashKey) {
        return redisTemplate.opsForHash().delete(key, hashKey);
    }

    /**
     * 获得缓存的基本对象列表.
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern) {
        return redisTemplate.keys(pattern);
    }

    /**
     * 通过scan游标扫描.
     *
     * @param match key 匹配
     * @return 游标
     */
    public Cursor<String> scan(final String match) {
        ScanOptions scanOptions = ScanOptions.scanOptions().match(match).build();
        RedisSerializer<String> redisSerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
        return (Cursor) redisTemplate.executeWithStickyConnection(redisConnection ->
                new ConvertingCursor<>(redisConnection.scan(scanOptions), redisSerializer::deserialize));
    }

}
